<?php

namespace App\Http\Controllers\Guard\Flight;

use App\Http\Controllers\Common\ApiController;
use App\Http\Requests\OrderRequest;
use App\Models\Flight\Order;
use App\Models\Rbac\GuardUser;
use App\Models\Site\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class OrderController extends ApiController{

    private $model = Order::class;

    public function getDefaultFlight(Request $request) {
        $val = Setting::query()->where('key','flight')->first()->val??'';
        return responseSuccess(compact('val'));
    }


    public function getOrderCode(Request $request) {

        return responseSuccess(['code'=>$this->getCode()]);
    }

    public function lst(Request $request) {

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $currentUser = GuardUser::where(compact('id'))->first();
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);

        $conditions = $request->input();

        $records = (new $this->model())->getLst($conditions);

        if($id==1){
            //$records = $records->where('writer',$id);
        }else{
            $ids = $currentUser->getBelowUser();
            $records = $records->whereIn('writer_id',$ids);
        }
        $records = $records->with(['getWriter:id,name','getFlightInfo','getCoupleFlightInfo']);

        if($request->has('del')){
            $records = $records->onlyTrashed();
        }
        $records = $records->paginate($pageSize,$this->getCol,'page',$page);

        foreach ($records as $record) {
            if(!isset($record->getFlightInfo))
                continue;

            if($record->is_double==1){
                $record->flight_no = $record->getFlightInfo->flight_no.'<=>'.$record->getFlightInfo->couple_flight_no;
                $record->date = $record->getFlightInfo->date.'<=>'.$record->getCoupleFlightInfo->date;
                $record->start_fly_time = $record->getFlightInfo->start_fly_time.' / '.$record->getCoupleFlightInfo->start_fly_time;
                $record->end_fly_time = $record->getFlightInfo->end_fly_time.' / '.$record->getCoupleFlightInfo->end_fly_time;
            }else{
                $record->flight_no = $record->getFlightInfo->flight_no;
                $record->date = $record->getFlightInfo->date;
                $record->start_fly_time = $record->getFlightInfo->start_fly_time;
                $record->end_fly_time = $record->getFlightInfo->end_fly_time;
            }
            $record->passenger_birthday = Str::replace('-', '/', $record->passenger_birthday);
            $record->created_at = Str::replace('-', '/', $record->created_at);
            $record->passenger_sex= $record->passenger_sex=='F'?'女':'男';
            $record->iswangfan= $record->iswangfan==1?'是':'否';
            $record->is_double= $record->is_double==1?'往返':'单程';
        }

        $currentAuth = $currentUser->role_ids??'';
        $currentAuth = empty($currentAuth)?[]:explode(',', $currentAuth);
        return responseSuccess($records->items(),$records->total(),100000,compact('currentAuth'));

    }

    public function add(OrderRequest $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        //dd($token,$id);
        $currentUser = GuardUser::where(compact('id'))->first();

        $info = $request->input();

        $count = $request->input('count');
        $flight_ids = $request->input('flight_ids');

        //如果不是往返程的，就只取第一个flight_id
        if(!$info['is_double']){
            $flight_ids = [$flight_ids[0]];
        }



        $code =  $info['code']??$this->getCode();
        $data = [];
        $time = date('Y-m-d H:i:s');
        for($i=0;$i<$count;$i++){
            foreach ($flight_ids as $k=>$flight_id) {
                $temp = [
                    'code'=>$code,
                    'name'=>strtoupper($info['name']??''),
                    'is_double'=>$info['is_double']?1:0,
                    'passport'=>$info['passport'],
                    'passenger_sex'=>$info['passenger_sex'],
                    'passenger_birthday'=>$info['passenger_birthday'],
                    'passenger_type'=>empty($info['passenger_birthday'])?'成人':getPassagerType($info['passenger_birthday']),
                    'flight_id'=>$flight_id,
                    'beizhu'=>$info['beizhu'],
                    'writer_id'=>$currentUser->id,
                    'created_at'=>$time,
                    'updated_at'=>$time,
                ];

                //如果是往返的
                if($info['is_double']){

                    //如果是“去”的航班
                    if($k==0){
                        $temp['is_hide'] = 0;
                        $temp['couple_flight_id'] = $flight_ids[1];
                    }else{
                        $temp['is_hide'] = 1;
                        $temp['couple_flight_id'] = $flight_ids[0];
                    }
                }
                //如果是单程的
                else{
                    $temp['is_hide'] = 0;
                    $temp['couple_flight_id'] = 0;
                }
                $data[] = $temp;
            }
        }
        //dd($data);
        Order::query()->insert($data);
        return responseSuccess();
    }

    public function edit(Request $request){
        $id = $request->input('id');
        $code = $request->input('code');
        $info = $request->input();
        $flight_ids = $request->input('flight_ids');

        if($info['is_double'] && (empty($flight_ids[0]) || empty($flight_ids[1])))
            return responseFail('航班不能为空！');


        Order::query()->where(compact('id'))->update([
            'name'=>$info['name'],
            /*'last_name'=>$info['last_name'],
            'first_name'=>$info['first_name'],*/
            'passenger_sex'=>$info['passenger_sex'],
            'passenger_birthday'=>$info['passenger_birthday'],
            'passenger_type'=>getPassagerType($info['passenger_birthday']),
            'passport'=>$info['passport'],
            'beizhu'=>$info['beizhu'],
            'flight_id'=>$info['flight_ids'][0],
            'couple_flight_id'=>$info['flight_ids'][1],
        ]);

        //再找到另一条隐藏的（也就是返程的数据）
        Order::query()->where(compact('code'))->where('id','!=',$id)->update([
            'name'=>$info['name'],
            /*'last_name'=>$info['last_name'],
            'first_name'=>$info['first_name'],*/
            'passenger_sex'=>$info['passenger_sex'],
            'passenger_birthday'=>$info['passenger_birthday'],
            'passenger_type'=>getPassagerType($info['passenger_birthday']),
            'passport'=>$info['passport'],
            'beizhu'=>$info['beizhu'],
            'flight_id'=>$info['flight_ids'][1],
            'couple_flight_id'=>$info['flight_ids'][0],
        ]);
        return responseSuccess();
    }

    public function beizhu(Request $request){
        $id = $request->input('id');
        $beizhu = $request->input('beizhu');
        Order::query()->where(compact('id'))->update([
            'beizhu'=>$beizhu
        ]);
        return responseSuccess();
    }

    private function getCode(){
        $codes =  Order::query()->pluck('code')->toArray();
        $code = generateRandomString();
        while (in_array($code,$codes)){
            $code = generateRandomString();
        }
        return strtoupper($code);
    }

    public function detail(Request $request){
        $id = $request->input('id',0);
        $records = $this->getDetail($this->model,[$id]);
        return responseSuccess($records->toArray(),1);
    }

    public function change(Request $request) {

        $ids = $request->input('ids',[]);
        $status = $request->input('status');
        return $this->changeColByIds($this->model, [$ids],compact('status'));
    }

    public function del(Request $request) {
        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $code = $request->input('code');

        //恢复数据
        if($request->has('back')){
            DB::table('order')->where('code', $code)->update(['writer_id'=>$id,'deleted_at'=>null]);
            //Order::onlyTrashed()->where('code',$code)->restore();
            //Order::query()->where('code', $code)->update(['writer_id'=>$id]);
            return responseSuccess();
        }
        //批量删除
        if($request->has('ids')){
            $ids = $request->input('ids',[]);
            foreach ($ids as $id) {
                $order = Order::query()->where(compact('id'))->first();
                if(empty($order))continue;
                else{
                    //删除
                    $code = $order->code;
                    Order::query()->where('code', $code)->update(['writer_id'=>$id,'deleted_at'=>date('Y-m-d H:i:s')]);
                }
            }
            return responseSuccess();
        }
        //单删
        else{
            Order::query()->where('code', $code)->update(['writer_id'=>$id,'deleted_at'=>date('Y-m-d H:i:s')]);
        }
        return responseSuccess();
    }
}
